package ar

import (
	"fmt"
	"godemo/common"
	"godemo/common/helper"
	"log"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

const PAGE_NUM = 3

type User struct {
	Username string `json:"userName" gorm:"comment:'用户登录名'"`
	Password string `json:"-" gorm:"comment:'用户登陆密码'"`
	Status   int32  `json:"status" gorm:"comment:'用户状态'"`
	gorm.Model
}

func (u User) FormatDate() string {
	return u.CreatedAt.Format("2006-01-02")
}

func (u User) DelLink() string {
	return fmt.Sprintf("/user/del?id=%d", u.ID)
}

func UserAdd(name string) uint {
	u := User{Username: name, Password: helper.Sha1String("123456")}
	res := common.SYS_DB.Create(&u)
	log.Println(res.Error)
	return u.ID
}

func GetByUsername(name string) (User, error) {
	var u User
	if err := common.SYS_DB.Where("username=?", name).First(&u).Error; err != nil {
		return u, err
	}
	return u, nil
}

func UserDel(id uint) {
	common.SYS_DB.Delete(&User{}, id)
}

func UserRows(c *gin.Context) ([]User, common.ViewData) {
	var users = []User{}
	db := common.SYS_DB.Model(&User{})
	pagers := common.PageNew(c, db, "/user/index")
	viewData := pagers.Paging()
	if err := pagers.Results(&users); err != nil {
		log.Println(err)
	}
	return users, viewData
}
